#!/usr/bin/python
# -*- coding: utf-8 -*-
#/*
# *      Copyright (C) 2011 Tolin
# *
# *
# *  This Program is free software; you can redistribute it and/or modify
# *  it under the terms of the GNU General Public License as published by
# *  the Free Software Foundation; either version 2, or (at your option)
# *  any later version.
# *
# *  This Program is distributed in the hope that it will be useful,
# *  but WITHOUT ANY WARRANTY; without even the implied warranty of
# *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# *  GNU General Public License for more details.
# *
# *  You should have received a copy of the GNU General Public License
# *  along with this program; see the file COPYING.  If not, write to
# *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# *  http://www.gnu.org/copyleft/gpl.html
# */
import urllib2, re, xbmc, xbmcgui, xbmcplugin, os, urllib, urllib2, socket

#socket.setdefaulttimeout(12)

h = int(sys.argv[1])
icon = xbmc.translatePath(os.path.join(os.getcwd().replace(';', ''),'icon.png'))
siteUrl = 'uakino.net'
httpSiteUrl = 'http://' + siteUrl
url1 = '1'


def construct_request(params):
	return '%s?%s' % (sys.argv[0], urllib.urlencode(params))

def showMessage(heading, message, times = 30000):
    xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")'%(heading, message, times, icon))





def strip_html(text):
	def fixup(m):
		text = m.group(0)
		if text[:1] == "<":
			if text[1:3] == 'br':
				return '\n'
			else:
				return ""
		if text[:2] == "&#":
			try:
				if text[:3] == "&#x":
					return chr(int(text[3:-1], 16))
				else:
					return chr(int(text[2:-1]))
			except ValueError:
				pass
		elif text[:1] == "&":
			import htmlentitydefs
			if text[1:-1] == "mdash":
				entity = " - "
			elif text[1:-1] == "ndash":
				entity = "-"
			elif text[1:-1] == "hellip":
				entity = "-"
			else:
				entity = htmlentitydefs.entitydefs.get(text[1:-1])
			if entity:
				if entity[:2] == "&#":
					try:
						return chr(int(entity[2:-1]))
					except ValueError:
						pass
				else:
					return entity
		return text
	ret =  re.sub("(?s)<[^>]*>|&#?\w+;", fixup, text)
	return re.sub("\n+", '\n' , ret)

def GET(url):
	try:
	    print 'def GET(%s):'%url
	    req = urllib2.Request(url)
	    req.add_header('User-Agent', 'Opera/10.60 (X11; openSUSE 11.3/Linux i686; U; ru) Presto/2.6.30 Version/10.60')
	    req.add_header('Accept', 'text/html, application/xml, application/xhtml+xml, */*')
	    req.add_header('Accept-Language', 'ru')
	    f = urllib2.urlopen(req)
	    a = f.read()
	    f.close()
	    return a
	except:
	    showMessage('Не могу открыть URL', url)
	    return None




def ROOT1():
#	wurl = 'http://uakino.net/videoclip'
#	http = GET(wurl)
	wurl = httpSiteUrl + urllib.unquote_plus(params['href'])
	http = GET(wurl)
	if http == None: return False
	r0= re.compile('<div id="kategorien">(.*?)<div class="col-m media">',re.S).findall(http)
	r1 = re.compile('<a href="(.*?)">\s*(.*?)\s*</a>').findall(r0[0])
	if len(r1) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	for href, name in r1:
		name = strip_html(name)
		i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
		u  = sys.argv[0] + '?mode=OPEN_MOVIES'
		u += '&url=%s'%urllib.quote_plus(httpSiteUrl + '/'  + href)
#		u += '&name=%s'%urllib.quote_plus(name)
		xbmcplugin.addDirectoryItem(h, u, i, True)
	xbmcplugin.endOfDirectory(h)

def ROOT():
	
	li = xbmcgui.ListItem('Видео')
	uri = construct_request({
		'mode': 'ROOT1',
		'href':  '/video'
	})
	xbmcplugin.addDirectoryItem(h, uri, li, True)

	li = xbmcgui.ListItem('Видеоклипы')
	uri = construct_request({
		'mode': 'ROOT1',
		'href': '/videoclip'
	})
	xbmcplugin.addDirectoryItem(h, uri, li, True)

	li = xbmcgui.ListItem('Зарубежные сериалы')
	uri = construct_request({
		'mode': 'OPEN_SER',
		'url': 'http://uakino.net/category/video/66'
	})
	xbmcplugin.addDirectoryItem(h, uri, li, True)
	
	li = xbmcgui.ListItem('Русские сериалы')
	uri = construct_request({
		'mode': 'OPEN_SER',
		'url': 'http://uakino.net/category/video/67'
	})
	xbmcplugin.addDirectoryItem(h, uri, li, True)
	
#	name='Поиск'
#       li = xbmcgui.ListItem(name)
#        url = sys.argv[0] + '?mode=ROOT1'
#        xbmcplugin.addDirectoryItem(h, url, li, True)
	
	xbmcplugin.endOfDirectory(h)





def OPEN_MOVIES(params):
	http = GET(urllib.unquote_plus(params['url']))
#	showMessage('param url1', (params['url1']))
	if http == None: return False
	r1 = re.compile('<div class="content">(.*?)<div id="ad_bottom"><noindex>',re.S).findall(http)
	rows = re.compile('<a href="(.*?)" class="preview"><img src="(.*?)" height="120" alt="(.*?)" /></a>').findall(r1[0])
	if len(rows) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов href, img, alt')
		return False
	for href, img, alt in rows:
			img = img
#			showMessage('ПК',img)
			alt = strip_html(alt)
			i = xbmcgui.ListItem(alt, iconImage=img, thumbnailImage=img)
			u  = sys.argv[0] + '?mode=PLAY'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl + '/' + href)
			i.setProperty('IsPlayable', 'true')
			xbmcplugin.addDirectoryItem(h, u, i)
	try:
		rp = re.compile('<span class="sort">(.*?)<span class="count">', re.DOTALL).findall(http)[0]
		rp2 = re.compile('<a href="(.*?)">(.*?)</a>').findall(rp)
		for href, nr in rp2[:-1]:
			u = sys.argv[0] + '?mode=OPEN_MOVIES'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl +'/'+ href)
#			rPN = '[B][COLOR yellow]%s[/COLOR][/B]' % rPN
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass

	xbmcplugin.endOfDirectory(h)

def OPEN_SER(params):
	http = GET(urllib.unquote_plus(params['url']))
#	showMessage('mov', params['url'])
	if http == None: return False
	r1 = re.compile('<div class="content">(.*?)<div id="ad_bottom"><noindex>',re.S).findall(http)
	rows = re.compile('<a href="(.*?)" class="preview"><img src="(.*?)" height="120" alt="(.*?)" /></a>').findall(r1[0])
	if len(rows) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов href, img, alt')
		return False
	for href, img, alt in rows:
			img = img
#			showMessage('ПК',img)
			alt = strip_html(alt)
			i = xbmcgui.ListItem(alt, iconImage=img, thumbnailImage=img)
			u  = sys.argv[0] + '?mode=OPEN_MOVIES'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl + '/' + href)
#			i.setProperty('IsPlayable', 'true')
			xbmcplugin.addDirectoryItem(h, u, i, True)
	try:
		rp = re.compile('<span class="sort">(.*?)<span class="count">', re.DOTALL).findall(http)[0]
		rp2 = re.compile('<a href="(.*?)">(.*?)</a>').findall(rp)
		for href, nr in rp2[:-1]:
			u = sys.argv[0] + '?mode=OPEN_SER'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl +'/'+ href)
#			rPN = '[B][COLOR yellow]%s[/COLOR][/B]' % rPN
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass

	xbmcplugin.endOfDirectory(h)


def OPEN_MOV(params):
	http = GET(urllib.unquote_plus(params['url']))
	if http == None: return False

	rows = re.compile('<a href="(.+?)" class="preview"><img src="(.+?)" height="120" alt="(.+?)" /></a>').findall(http)
	if len(rows) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов href, img, alt')
		return False
	for href, img, alt in rows:
			img = 'http://uakino.net/' + img
#			alt = strip_html(alt)
			i = xbmcgui.ListItem(alt, iconImage=img, thumbnailImage=img)
			u  = sys.argv[0] + '?mode=PLAY'
			u += '&url=%s'%urllib.quote_plus('http://uakino.net/' + href)
			i.setProperty('IsPlayable', 'true')
			xbmcplugin.addDirectoryItem(h, u, i)

	xbmcplugin.endOfDirectory(h)



def PLAY(params):
	http = GET(urllib.unquote_plus(params['url']))
#	showMessage('play', params['url'])
	if http == None: return False
	rows1 = re.compile('<meta property="og:video" content="(.+?)">').findall(http)
#	showMessage('ПО', rows1)
	if len(rows1) == 0:
#		ROOT1()
#		url = 'url=%s'%urllib.quote_plus(params['url'])
#		url = (params['url'])
#		showMessage('url1', url)
#		OPEN_MOVIES(url)
		showMessage('Упс', 'Нет видеофайла')
		return False
	i = xbmcgui.ListItem(path = rows1[0])
#showMessage('ПОi', i)
	xbmcplugin.setResolvedUrl(h, True, i)

def get_params(paramstring):
	param=[]
	if len(paramstring)>=2:
		params=paramstring
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]
	return param

params=get_params(sys.argv[2])


mode = None

try:
	mode = urllib.unquote_plus(params['mode'])
except:


#getCategories(params)
	ROOT()

if mode == 'video_sub': video_sub()
if mode == 'clip_sub': clip_sub()
if mode == 'audio': audio()
if mode == 'genre': genre()

if mode == 'ROOT1': ROOT1()

if mode == 'OPEN_MOVIES':
	OPEN_MOVIES(params)
if mode == 'OPEN_SER':
	OPEN_SER(params)

if mode == 'PLAY':
	PLAY(params)
